package com.zxt.dao.impl;

import com.zxt.dao.AddressDao;
import com.zxt.domain.Address;
import com.zxt.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    private QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public List<Address> select(Integer uid) {
        String sql=" select * from tb_address where uid=? ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Address.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void insert(Address address) {
        String sql="insert into tb_address (detail,name,phone,uid,level) values (?,?,?,?,?) ";
        Object[] params={address.getDetail(),address.getName(),address.getPhone(),address.getUid(),address.getLevel()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer uid, Integer aid) {
        String sql=" delete from tb_address where id=? and uid=? ";
        try {
            queryRunner.update(sql,aid,uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateLevel(Integer uid, Integer aid) {
        try {
           queryRunner.update(" update tb_address set level=0 where uid=? ",uid);
           queryRunner.update(" update tb_address set level=1 where id=? and uid=? ",aid,uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Address address) {
        String sql=" update tb_address set detail=?,name=?,phone=?,uid=?,level=? where id=? ";
        Object[] params={address.getDetail(),address.getName(),address.getPhone(),address.getUid(),address.getLevel(),address.getId()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
